package cn.ffcs.uec.outStaffDataModificationApply.component;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Div;
import org.zkoss.zul.Window;

import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.uec.organization.manager.UecOrgDeptManager;
import cn.ffcs.uec.organization.manager.UecOrgOrgsManager;
import cn.ffcs.uec.organization.model.UecOrgDept;
import cn.ffcs.uec.organization.model.UecOrgOrgs;
import cn.ffcs.uec.outStaff.constant.UecOutStaffConstants;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.outStaff.vo.UecOutStaffInfoVo;
import cn.ffcs.uec.outStaffDataModificationApply.component.bean.UecOutStaffWorkDateModificationListboxExtBean;
import cn.ffcs.uec.outStaffEntryApply.component.OutStaffEntryApplyListboxExt;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.staff.manager.UecTrialManager;
import cn.ffcs.uec.staff.model.UecTrial;
import cn.ffcs.uom.common.constants.BaseUnitConstants;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.PlatformUtil;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;

@Controller
@Scope("prototype")
public class UecOutStaffWorkDateModificationListboxExt extends Div implements
		IdSpace {

	private static final long serialVersionUID = 1032836071218404217L;

	private UecOutStaffWorkDateModificationListboxExtBean bean = new UecOutStaffWorkDateModificationListboxExtBean();

	private static final String OUT_STAFF_WORKDATE_MODIFICATION_APPLY_LISTBOX_EXT_ZUL = "/pages_nmg/outStaffDataModificationApply/comp/outStaffWorkDateModificationApply_listbox_ext.zul";

	private UecOutStaffInfo uecOutStaffInfo;

	private UecOutStaffInfo qryUecOutStaffInfo;

	private UecTrial qryUecTrial;

	private UecTrialManager uecTrialManager = (UecTrialManager) ApplicationContextUtil
			.getBean("uecTrialManager");
	private UecOrgDeptManager uecOrgDeptManager = (UecOrgDeptManager) ApplicationContextUtil
			.getBean("uecOrgDeptManager");
	private UecOrgOrgsManager uecOrgOrgsManager = (UecOrgOrgsManager) ApplicationContextUtil
			.getBean("uecOrgOrgsManager");

	/**
	 * 外包人员虚拟对象
	 */
	private UecOutStaffInfoVo uecOutStaffInfoVo;

	public UecOutStaffWorkDateModificationListboxExt() {
		Executions.createComponents(
				OUT_STAFF_WORKDATE_MODIFICATION_APPLY_LISTBOX_EXT_ZUL, this,
				null);
		Components.wireVariables(this, bean);
		Components.addForwards(this, this, '$');
	}

	public void onCreate() {
		bean.getSaveOutStaffButton().setDisabled(true);
	}

	/**
	 * 查询按钮 根据条件查询
	 * 
	 * @throws Exception
	 * @throws SuspendNotAllowedException
	 */
	public void onQuery() throws SuspendNotAllowedException, Exception {
		clearVariable();
		PubUtil.clearComponent(this.bean.getBasePanel());
		uecOutStaffInfoVo = new UecOutStaffInfoVo();
		/**
		 * 组织树Ext UecOrganizationTreeBandboxExt 组织树上有组织和部门 通过组织树获取组织或部门
		 */
		if (!StrUtil.isNullOrEmpty(bean.getOutStaffPkHrorg().getValue())) {
			// 组织类型：公司 or 部门
			String orgType = (String) bean.getOutStaffPkHrorg()
					.getOrganization().getOrgType();
			// 组织主键
			String pkorg = (String) bean.getOutStaffPkHrorg().getOrganization()
					.getOrg();
			
			if ("ORG".equals(orgType)) {
				// 公司
				String orgName = (String) bean.getOutStaffPkHrorg().getOrganization()
						.getOrgName();
				//uecOutStaffInfoVo.setPkOrg(pkorg);
		       	 if("中国电信股份有限公司内蒙古分公司".equals(orgName)) {
		       		uecOutStaffInfoVo
		       		.setOrgName(null);
		       	}else if(orgName.endsWith("*")){
		       		uecOutStaffInfoVo
		       		.setOrgName(orgName);
		       	}else {
		       		uecOutStaffInfoVo.setPkOrg(pkorg);
		       	}
			} else {
				UecOrgDept uecOrgDept = new UecOrgDept();
				UecOrgOrgs uecOrgOrgs = new UecOrgOrgs();
				uecOrgDept.setPkDept(pkorg);
				uecOrgDept = uecOrgDeptManager.findUecOrgDeptByOrgDept(uecOrgDept);
				// 部门所属公司
				if(uecOrgDept !=null) {
					uecOrgOrgs= new UecOrgOrgs();
					uecOrgOrgs.setPkOrg(uecOrgDept.getPkOrg());
					uecOrgOrgs = uecOrgOrgsManager.findUecOrgOrgsByUecOrgOrgs(uecOrgOrgs);
					String orgName=uecOrgOrgs.getName();
					uecOutStaffInfoVo.setPkDept(uecOrgDept.getPkDept());
					uecOutStaffInfoVo.setPkOrg(uecOrgDept.getPkOrg());
					uecOutStaffInfoVo.setOrgName(orgName);

				//uecOutStaffInfoVo.setPkDept(pkorg);
			}

			}
		}
		uecOutStaffInfoVo.setStaffCode(bean.getOutStaffCode().getValue());
		uecOutStaffInfoVo.setStaffName(bean.getOutStaffName().getValue());
		uecOutStaffInfoVo.setIdNum(bean.getOutStaffIdNum().getValue());
		outStaffList();

	}

	/**
	 * 员工列表
	 * 
	 * @throws Exception
	 * @throws SuspendNotAllowedException
	 */

	public void outStaffList() throws SuspendNotAllowedException, Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("opType", "outStaffList");
		map.put("uecOutStaffInfoVo", uecOutStaffInfoVo);
		Window window = (Window) Executions.createComponents(
				UecOutStaffConstants.UEC_OUT_STAFF_LIST_ZUL, this, map);
		window.doModal();
		window.addEventListener("onOK", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				if (event.getData() != null) {
					qryUecOutStaffInfo = (UecOutStaffInfo) event.getData();
					bean.getSaveOutStaffButton().setDisabled(false);
					/**
					 * 每个员工只有一次转正申请
					 */
					qryUecTrial = UecTrial.newInstance();
					qryUecTrial.setStaffId(qryUecOutStaffInfo.getOutStaffId());
					qryUecTrial
							.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
					qryUecTrial = uecTrialManager.findUecTrial(qryUecTrial);
					// 判断 人员试用情况是否为null
					if (!StrUtil.isNullOrEmpty(qryUecTrial)) {
						PubUtil.fillBeanFromPo(qryUecOutStaffInfo, bean);
						bean.getOldJoinWorkDate().setValue(
								qryUecOutStaffInfo.getJoinWorkDate());
						bean.getOldGlbdef3().setValue(
								qryUecOutStaffInfo.getGlbdef3());
						bean.getOldEnterUnitTime().setValue(
								qryUecOutStaffInfo.getEnterUnitTime());

						// bean.getJoinWorkDate().setValue(DateUtil.strToDate(qryUecOutStaffInfo.getJoinWorkDate()));
						// bean.getGlbdef3().setValue(DateUtil.strToDate(qryUecOutStaffInfo.getGlbdef3()));
						// bean.getEnterUnitTime().setValue(DateUtil.strToDate(qryUecOutStaffInfo.getEnterUnitTime()));

						// 判断PkHrorg是否为空
						if (!StrUtil.isNullOrEmpty(qryUecOutStaffInfo
								.getPkHrorg())) {
							bean.getOrgName()
									.setValue(
											uecOrgOrgsManager
													.getUecOrgOrgsNameByPkOrg(qryUecOutStaffInfo
															.getPkHrorg()));
							uecOutStaffInfo = qryUecOutStaffInfo;
						} 
					} else {
						ZkUtil.showError("此人未入职,请先执行入职操作", "温馨提示");
					}
				}
			}
		});
	}

	/**
	 * 重置按钮
	 */
	public void onReset() {
		PubUtil.clearComponent(this);
		bean.getSaveOutStaffButton().setDisabled(true);
	}

	/**
	 * 保存工作日期信息
	 */
	public void onSave() {
		// 获取登录用户
		String currentName = "";
		if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
			ZkUtil.showError("当前登录用户已经失效，请重新登录系统", "错误提示");
			return;
		} else {
			currentName = PlatformUtil.getCurrentUser().getScreenName();
		}
		if (StrUtil.isNullOrEmpty(bean.getJoinWorkDate().getValue())) {
			ZkUtil.showError("参加工作日期未填写！", "错误提示");
			return;
		}
		if (StrUtil.isNullOrEmpty(bean.getGlbdef3().getValue())) {
			ZkUtil.showError("进入电信系统日期未填写!", "错误提示");
			return;
		}
		if (StrUtil.isNullOrEmpty(bean.getEnterUnitTime().getValue())) {
			ZkUtil.showError("进入本单位时间未填写！", "错误提示");
			return;
		}
		// PubUtil.fillPoFromEditorBean(uecOutStaffInfo, bean);
		uecOutStaffInfo.setJoinWorkDate(DateUtil.dateToStr(bean
				.getJoinWorkDate().getValue()));
		uecOutStaffInfo.setGlbdef3(DateUtil.dateToStr(bean.getGlbdef3()
				.getValue()));
		uecOutStaffInfo.setEnterUnitTime(DateUtil.dateToStr(bean
				.getEnterUnitTime().getValue()));

		// if (!StrUtil.isNullOrEmpty(bean.getRetireDate().getValue())) {
		// uecOutStaffInfo.setRetireDate(DateUtil.dateToStr(bean
		// .getRetireDate().getValue()));
		// }
		
		/**
		 * 修改取数据方式  bmp
		 */
		// 工龄
		/*Integer workYears = OutStaffEntryApplyListboxExt
				.getWorkingYears(qryUecOutStaffInfo.getJoinWorkDate());*/
		Integer workYears = OutStaffEntryApplyListboxExt
				.getWorkingYears(uecOutStaffInfo.getJoinWorkDate());
		uecOutStaffInfo.setDef3(workYears.toString());
		// 本企业工龄：当前日期 – 进入本单位日期
		Integer theWorkYears = OutStaffEntryApplyListboxExt
				.getWorkingYears(uecOutStaffInfo.getEnterUnitTime());
		uecOutStaffInfo.setDef4(theWorkYears.toString());
		// 预计退休日期：男=出生日期+60年;女=出生日期+50年
		/*
		 * Date retiredDate = OutStaffEntryApplyListboxExt.getRetiredDate(
		 * qryUecOutStaffInfo.getSex(), qryUecOutStaffInfo.getIdNum());
		 * uecOutStaffInfo.setGlbdef15(new SimpleDateFormat("yyyy-MM-dd")
		 * .format(retiredDate));
		 */
		// 设置修改人、修改时间
		uecOutStaffInfo.setModifier(currentName);
		uecOutStaffInfo.setModifiedTime(DateUtil.getCurrenDate());
		// uecTitle = UecTitle.newInstance();
		// uecTitle.setStaffId(uecOutStaffInfo.getOutStaffId());
		// uecTitle = uecTitleManager.findUecTitle(uecTitle);

		// 发起流程
		if (ApprovalUtil.getActivityFlag()) {
			// 判断该人员是否在审状态，如果是在审状态不允许再次发起此流程
			boolean isOnApproval = ApprovalUtil.isOnApproval(
					ApprovalConstants.OUT_STAFF_WORK_DATE_EDIT_PROC_DEF_ID,
					uecOutStaffInfo.getOutStaffId());
			if (isOnApproval) {
				ZkUtil.showError("在审状态不允许发起！", "错误提示");
				return;
			}
			if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
				ZkUtil.showError("当前登录用户不存在!", "错误提示");
				return;
			}
			// uec_out_staff_info 修改一条记录
			// 数据入库
			Long uecOutStaffIdHis = uecOutStaffInfo.getOutStaffId();
			uecOutStaffInfo.addStatusCdIS3();
			Long uecOutStaffId = uecOutStaffInfo.getOutStaffId();

			// Long uecTitleIdHis = uecTitle.getTitleId();
			// uecTitle.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
			// uecTitle.setStaffId(uecOutStaffIdHis);
			// uecTitle.setPkTechposttitle(bean.getTitleTechpost().getValue());
			// uecTitle.addStatusCdIS3();
			// Long uecTitleId = uecTitle.getTitleId();

			String formTheme = "盟市外包人员工作日期修改流程";

			String startFlowJson = "{" + "formTheme: '" + formTheme + "',"
					+ " formContent: '工作日期修改人员:" + uecOutStaffInfo.getPsnName()
					+ "'," + " procDefId: '"
					+ ApprovalConstants.OUT_STAFF_WORK_DATE_EDIT_PROC_DEF_ID
					+ "'," + " urgent: '1'," + " atiActCategoryId: '"
					+ ApprovalConstants.MODIFICATION_CATEGORY_ID + "',"
					+ " procDefKey: '" + ApprovalUtil.OUT_STAFF_WORKDATE_EDIT
					+ "'," + " formSender: '" + currentName + "',"
					+ " primaryId: '{" + "uec_out_staff_info_his:"
					+ uecOutStaffIdHis + ",uec_out_staff_info:" + uecOutStaffId
					+ "'}";

			String procInstId = null;
			try {
				procInstId = ApprovalUtil.startApproval(startFlowJson);
			} catch (Exception e) {
				// 流程发起失败 数据改为失效
				uecOutStaffInfo.removeOnly();
				// uecTitle.removeOnly();
				onReset();
				ZkUtil.showError("流程发起失败！", "错误提示");
				e.printStackTrace();
			}

			if (StrUtil.isNullOrEmpty(procInstId)) {
				uecOutStaffInfo.removeOnly();
				// uecTitle.removeOnly();
				onReset();
				ZkUtil.showError("流程发起失败！", "错误提示");
				return;
			}

			// 第一审批人如果是发起人直接到人力审批环节
			ApprovalUtil.isCurrentAssignNames(procInstId);

			ApprovalUtil.showNextAssignee(procInstId, formTheme);

		} else {
			uecOutStaffInfo.updateOnly();
			ZkUtil.showInformation("数据保存成功", "温馨提示");
		}

		onReset();
	}

	/**
	 * 清除变量
	 */
	public void clearVariable() {
		uecOutStaffInfoVo = null;
		qryUecOutStaffInfo = null;
		uecOutStaffInfo = null;
	}

}
